package gin

import (
	"fmt"
	"net/http"
	"strings"
)


type router struct {
	mroots map[string]*root
	mhandlers map[string]HandlerFunc
}

func newRouter() *router{
	r := &router{
		mroots: make(map[string]*root),
		mhandlers: make(map[string]HandlerFunc),
	}
	r.mroots["GET"] = newRoot()
	r.mroots["POST"] = newRoot()
	return r
}


func (r *router) insert(method string,path string,f Handler) {
	path = strings.TrimRight(path,"/")
	fmt.Println(path)
	key := method + "+" + path
	r.mhandlers[key] = f.HandlerHttp
	r.mroots[method].add(path)
}


// 对于给定path进行服务
// 2.通过tri树找到--对于的handler加入c执行队列
// 解析匹配到的参数---支持restful
// 3.调用c.next执行
func (r *router) serve(ctx *Ctx) {
	method := ctx.GetMethod()
	url := ctx.GetUrl()
	n := r.mroots[method].find(url)
	if n==nil {
		// 没有找到匹配路径
		// 进行错误处理
		// fmt.Println("404")
		// ctx.SetStatus(http.StatusNotFound)
		ctx.Next()
		ctx.Text(http.StatusNotFound,"404 Not Found!")
		return 
	}

	key := method + "+" + n.pattern
	// 解析参数--放入ctx中
	surl := strings.Split(url,"/")[1:]
	sp := strings.Split(n.pattern,"/")[1:]

	for i:=0;i<len(sp);i++ {
		if sp[i][0]==':' {
			ctx.setRestful(sp[i][1:],surl[i])
		}
		if sp[i] == "*" {
			ctx.setRestful("*",strings.Join(surl[i:],"/"))
		}
	}

	f := r.mhandlers[key]
	ctx.addMid(f)
	ctx.Next()
	
}

